package com.yunxiangyue.musicplayer

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.provider.MediaStore
import android.text.BoringLayout
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import com.yunxiangyue.app.R
import com.yunxiangyue.logger.Logger
import com.yunxiangyue.server.ConnectExample
import com.yunxiangyue.server.OkHttpKeyUtil
import org.json.JSONObject
import java.io.*
import java.nio.charset.StandardCharsets
import java.util.ArrayList



//class Music(var num:String,var musicName:String,var play:String,var album:String){}
//class info(var flag:Boolean,var size: Int):Serializable{}
//var info_obj=info(true,1)

//class Music(var num:String,var musicName:String,var play:String){}
data class Music(var num:String,var musicName:String,var play:String) : Serializable {

//    override fun describeContents(): Int {
//        return 0
//    }
//
//    override fun writeToParcel(dest: Parcel, flags: Int) {
//        dest.writeString(num)
//        dest.writeString(musicName)
//        dest.writeString(play)
//    }
//
//    @Suppress("unchecked_cast")
//    public companion object CREATOR : Parcelable.Creator<Music> {
//        override fun createFromParcel(source: Parcel): Music {
//            return Music(
//                source.readString(),
//                source.readString(),
//                source.readString()
//            )
//        }
//
//        override fun newArray(size: Int): Array<Music?> {
//            return arrayOfNulls(size)
//        }
//    }

}

//var music_num=0


class music_play_list : AppCompatActivity(), Music_list_adapter.OnItemClickListener{

    private var musicList=ArrayList<Music>()
    var binder:MusicService.musicBinder?=null
    lateinit var  adapter:Music_list_adapter
    val TAG = "music_play_list"

    //将从服务端读取到的map集合分别赋给两个列表   ：歌曲名以及歌曲对应的字节数组
    var newMusicNameList =  mutableListOf<String>()

    var MusicNameList = mutableListOf<String>()
    var MusicPlayerList = mutableListOf<String>()


    //回调函数的定义  byteArray内存储的是请求返回的音乐集合字节数组   集合map<String,ByteArray>
    val getMusicInfoCallback: (Boolean,ByteArray) -> Unit = { result,byteArray ->
        if(result){   //获取数据响应成功
            Log.d(TAG,"数据响应成功")
            //将字节数组转换为map集合
            try {
                Log.d(TAG,"在这里")
                val jsonString = String(byteArray, StandardCharsets.UTF_8)
                val jsonO = JSONObject(jsonString)
                val musicCount = jsonO.getString("musicCount").toInt()
                //遍历json对象的键，获取对应的音乐名称
                var count = 1
                //只要json对象所取得音乐名称不为空字符则循环
                while(count <= musicCount){
                    newMusicNameList.add(jsonO.getString(count.toString()))
                    count = count +1

                }
//                Log.d(TAG,jsonO.getString("11"))
                Log.d(TAG,newMusicNameList.toString())
                var fileName:String = ""

                //对列表每一项进行拆分为歌曲名和演唱者
                for (i in 0..newMusicNameList.size - 1){
                    fileName = newMusicNameList.get(i)
                    MusicPlayerList.add(fileName.split(" - ").get(0))
                    MusicNameList.add(fileName.split(" - ").get(1).split(".").get(0))
                }
                for(i in 0..newMusicNameList.size - 1){
                    musicList.add(Music("${i+1}",MusicNameList.get(i),MusicPlayerList.get(i)))
                }
                runOnUiThread {
                    val music_list = findViewById<RecyclerView>(R.id.music_list)
                    val layoutManager=LinearLayoutManager(this)
                    music_list.layoutManager = layoutManager
                    val adapter = Music_list_adapter(musicList)
                    music_list.adapter = adapter
                    adapter.setOnItemClickListener(this)
                }
                Log.d(TAG,MusicNameList.toString())
                Log.d(TAG,MusicPlayerList.toString())
            }catch (e:StreamCorruptedException){
                e.printStackTrace()
                Log.d(TAG,e.message.toString())
            }
        }else{
            Log.d(TAG,"数据响应失败")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_music_play_list)
//        val music_list = findViewById<RecyclerView>(R.id.music_list)

//        startBinder()
//        getMusic()
        //创建歌单列表时，客户端发送获取音乐的请求，在回调函数中获取音乐资源
        val connectExample:ConnectExample = ConnectExample()
        connectExample.getAllMp3(OkHttpKeyUtil.KEY_GET_ALL_MP3,getMusicInfoCallback)   //OkHttpKeyUtil.KEY_GET_ALL_MP3代表获取所有的音乐文件,传给服务端

        Log.d(TAG,"musicList :"+musicList.toString())
//        val layoutManager=LinearLayoutManager(this)
//        music_list.layoutManager=layoutManager
//        val adapter=Music_list_adapter(musicList)
//        music_list.adapter = adapter
        val actionBar = supportActionBar
        if(actionBar != null) {
            actionBar.hide()
        }

//        adapter.setOnItemClickListener(this)
        findViewById<Button>(R.id.back).setOnClickListener {
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG,"onResume")
        Log.d(TAG,musicList.toString())
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }


    fun alertImg(){
        var num=intent.getIntExtra("num",0)
        if(num!=0){
            val back1 = findViewById<ImageView>(R.id.back1)
            val textLove = findViewById<TextView>(R.id.textLove)
            when(num){
                1-> {
                    back1.setImageResource(R.drawable.b1)
                    textLove.text="爱死我霉啦啊啊啊啊\uD83D\uDC97"
                }
                2 -> {
                    back1.setImageResource(R.drawable.background4)
                    textLove.text="Hiphop  \uD83D\uDDA4Rap"
                }
                3 -> {
                    back1.setImageResource(R.drawable.b2)
                    textLove.text="娱乐背景歌\uD83C\uDF3C"
                }
                4 -> {
                    back1.setImageResource(R.drawable.b3)
                    textLove.text="Isaac Dunbar"
                }
                5 ->{
                    back1.setImageResource(R.drawable.b4)
                    textLove.text="Bass万岁 |  贝斯手们站起来了！"
                }
                6 ->{
                    back1.setImageResource(R.drawable.b5)
                    textLove.text="放克灵魂| Funk Plaza | Bass..."
                }
                7 ->{
                    back1.setImageResource(R.drawable.b6)
                    textLove.text="【 女声金属 】悍妇女汉子的摇滚"
                }
                8 ->{
                    back1.setImageResource(R.drawable.b7)
                    textLove.text="氛围蒸汽波\uD83D\uDC97蹦迪少女的粉色臆想"
                }
            }
        }
    }


    fun getMusic() {
//        val cursor=contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,null)
//        cursor?.apply {
//            while(moveToNext()) {
//                val musicPath=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
//                val musicName=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE))
//                val musicSinger=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST))
//                val musicAlbum=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM))
//                musicNameLis.add(musicName)
//                musicSingerLis.add(musicSinger)
//                musicAlbumLis.add(musicAlbum)
//                musicPathLis.add(musicPath)
//            }
//            close()
//        }
    }

    override fun onDestroy() {
        super.onDestroy()
//        unbindService(this)
    }



    //    实现适配器中的点击事件方法
    override fun onItemClick(view: View?, position: Int) {
        var intent=Intent(this,music_playing::class.java)
        var click_item = musicList.get(position)
//        val connectExample:ConnectExample = ConnectExample()
        val musicName = click_item.musicName
        Logger.debug(TAG, "musicList size = ${musicList.size}, musicName = $musicName")
        intent.putExtra(INTENT_KEY_MUSIC_NAME,musicName)
        intent.putExtra(INTENT_KEY_MUSIC_LIST,musicList)
        startActivity(intent)
//        connectExample.getMusicByName(musicName) { result,byteArray ->
//            if(result){
//                val tempFile = File.createTempFile("audio", ".mp3", this.cacheDir)
//                tempFile.deleteOnExit() // 确保应用退出时删除文件
//                try {
//                    val fos = FileOutputStream(tempFile)
//                    fos.write(byteArray)
//                } catch (e: IOException) {
//                    e.printStackTrace()
//                    // 处理错误
//                }
////                val fileUri = Uri.fromFile(tempFile)
////                var bundle = Bundle()
//                intent.putExtra(INTENT_KEY_MUSIC_NAME,musicName)
//                intent.putExtra(INTENT_KEY_MUSIC_LIST,musicList)
//                Log.d(TAG,musicName+":" + musicList.toString())
//                startActivity(intent)
//            }else{
//                Log.e(TAG,"请求失败")
//            }
//        }
    }

    override fun onItemLongClick(view: View?, position: Int) {

    }
//    private fun startBinder() {
//        val intent=Intent(this,MusicService::class.java)
//        bindService(intent,this, Context.BIND_AUTO_CREATE)
//    }
//
//    override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
//        var binder=p1 as MusicService.musicBinder
//        if(binder!=null){
//            thread {
//                while (binder!=null){
//                    Thread.sleep(100)
//                    runOnUiThread {
//                        binder?.also {
//                            musicName.text=it.musicName
//                        }
//                    }
//                }
//            }
//        }
//    }
//
//    override fun onServiceDisconnected(p0: ComponentName?) {
//        binder=null
//    }
}